import { defineComponent, ref, computed, watch, createVNode } from 'vue';
import { FeatherChevronDown } from 'cui-vue-icons/feather';
import Tree from '../../Tree/index.js';
import Dropdown from '../../Dropdown/index.js';
import { Value } from '../../inner/Value.js';
import formFieldRef from '../../use/formFieldRef.js';
import { TreeCheckMod } from '../../Tree/store.js';

const index = /* @__PURE__ */ defineComponent({
  name: 'TreeSelect',
  props: {
    transfer: {
      type: Boolean,
      default: false
    },
    align: {
      type: String
    },
    disabled: {
      type: Boolean
    },
    clearable: {
      type: Boolean
    },
    prepend: {
      type: [Object, Number, String]
    },
    mode: {
      type: String
    },
    size: {
      type: String
    },
    showMax: {
      type: Number
    },
    valueClosable: {
      type: Boolean
    },
    placeholder: {
      type: String
    },
    showMore: {
      type: Boolean
    },
    multi: {
      type: Boolean
    },
    asFormField: {
      type: Boolean,
      default: true
    },
    emptyText: {
      type: String,
      default: '暂无数据'
    },
    data: {
      type: Array,
      default: () => []
    },
    checkable: {
      type: Boolean,
      default: false
    },
    checkRelation: {
      type: String,
      default: 'related'
    },
    directory: {
      type: Boolean,
      default: false
    },
    contextMenu: {
      type: Object
    },
    draggable: {
      type: Boolean,
      default: false
    },
    loadData: {
      type: Function
    },
    beforeDropMethod: {
      type: Function
    },
    beforeExpand: {
      type: Function
    },
    onNodeDragStart: {
      type: Function
    },
    onNodeDragEnter: {
      type: Function
    },
    onNodeDragOver: {
      type: Function
    },
    onNodeDragLeave: {
      type: Function
    },
    onSelectMenu: {
      type: Function
    },
    onChange: {
      type: Function
    },
    onContextMenu: {
      type: Function
    },
    modelValue: {
      type: Array
    },
    keyField: {
      type: String
    },
    titleField: {
      type: String
    },
    selectedClass: {
      type: String
    },
    draggingClass: {
      type: String
    },
    customIcon: {
      type: Function
    },
    arrowIcon: {
      type: Function
    }
  },
  emits: ['nodeSelect', 'nodeExpand', 'nodeCollapse', 'nodeChecked', 'change', 'update:modelValue', 'nodeDrop'],
  setup(props, {
    emit,
    expose
  }) {
    // 状态管理
    const innerValue = formFieldRef(props, emit, props.multi ? [] : '');
    const text = ref('');
    const treeRef = ref();
    const align = computed(() => props.align ?? 'bottomLeft');
    const mode = computed(() => props.mode ?? TreeCheckMod.HALF);
    const checkRelation = computed(() => props.checkRelation ?? 'related');

    // 类名处理
    const classList = computed(() => ({
      'cm-tree-select': true,
      'cm-tree-select-disabled': props.disabled,
      [`cm-tree-select-${props.size}`]: props.size
    }));

    // 事件处理
    const onSelect = data => {
      if (!props.multi) {
        innerValue.value = data[props.keyField || 'id'];
        emit('change', data[props.keyField || 'id']);
      }
    };
    const onTreeChange = ids => {
      innerValue.value = ids;
      emit('change', ids);
    };
    const onClear = () => {
      innerValue.value = props.multi ? [] : '';
      emit('change', innerValue.value);
    };
    const onValueClose = item => {
      if (Array.isArray(innerValue.value)) {
        const newValue = innerValue.value.filter(v => v !== item.id);
        innerValue.value = newValue;
      }
    };

    // 获取选中状态
    const getChecked = () => {
      return treeRef.value?.getCheckedKeys(mode.value) || [];
    };

    // 值变化监听
    watch(innerValue, (newVal, oldVal) => {
      updateText();
    });

    // 更新显示文本
    const updateText = () => {
      if (props.multi) {
        const all = treeRef.value?.getChecked(mode.value).map(item => ({
          id: item[props.keyField || 'id'],
          title: item[props.titleField || 'title']
        })) || [];
        text.value = all;
      } else {
        const data = treeRef.value?.getNode(innerValue.value);
        text.value = data?.[props.titleField || 'title'] || '';
      }
    };

    // 数据变化监听
    watch(() => props.data, () => {
      setTimeout(updateText);
    });

    // 暴露组件方法
    expose({
      getChecked,
      clear: onClear
    });
    return () => createVNode("div", {
      "class": classList.value,
      "tabindex": "1"
    }, [createVNode(Dropdown, {
      "transfer": props.transfer,
      "fixWidth": true,
      "align": align.value,
      "disabled": props.disabled,
      "trigger": "click",
      "menu": createVNode("div", {
        "class": "cm-tree-select-wrap"
      }, [createVNode(Tree, {
        "data": props.data,
        "checkable": props.multi,
        "onNodeSelect": onSelect,
        "onChange": onTreeChange,
        "ref": treeRef,
        "modelValue": props.multi ? innerValue.value : undefined,
        "selected": !props.multi ? innerValue.value : undefined,
        "checkRelation": checkRelation.value
      }, null)])
    }, {
      default: () => [createVNode(Value, {
        "text": text.value,
        "multi": props.multi,
        "showMax": props.showMax,
        "disabled": props.disabled,
        "showMore": props.showMore,
        "valueClosable": props.valueClosable,
        "clearable": props.clearable,
        "onClear": onClear,
        "prepend": props.prepend,
        "size": props.size,
        "icon": createVNode(FeatherChevronDown, null, null),
        "onClose": onValueClose
      }, null)]
    })]);
  }
});

export { index as default };
